﻿using SuperiorCommon;
using SuperiorModel;
using System;
using System.Web.Mvc;

namespace SuperiorShopkeeper
{
    /// <summary>
    /// 针对JSON请求的异常过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = true)]
    public class JsonExceptionAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                string controllerName = (string)filterContext.RouteData.Values["controller"];
                string actionName = (string)filterContext.RouteData.Values["action"];
                string msg = string.Format("Conrtoll:{0}------Action:{1}-----{2}", controllerName, actionName, filterContext.Exception.ToString());
                LogManger.Instance.WriteLog(msg);
                //返回异常JSON
                filterContext.Result = new JsonResult
                {
                    Data = new ResultModel(false, "网络异常"),
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                filterContext.ExceptionHandled = true;//不加这个，浏览器会帮你继续处理异常，就不会返回JSON
                return;
            }
        }
    }
}